<template>

  <div>
    <el-card>

      <baidu-map
        class="map"
        :center="currentCenter"
        :zoom="22"
        :scroll-wheel-zoom="true"
      >

        <bm-control
          anchor="BMAP_ANCHOR_TOP_RIGHT"
          :offset="{width:20,height:30}"
        >
          <el-button-group>
            <el-button
              size="small"
              type="primary"
              @click="handleCreate"
            >添加单位</el-button>
            <el-dropdown
              trigger="click"
              @command="handleChooseUnit"
            >
              <el-button size="small" type="primary">
                已部署单位<i class="el-icon-arrow-down el-icon--right" />
              </el-button>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="(unit , i) in unitList"
                  :key="i in unitList"
                  :command="i"
                >
                  {{ unit.name }}
                </el-dropdown-item>

              </el-dropdown-menu>
            </el-dropdown>
          </el-button-group>

        </bm-control>

        <div
          v-for="(unit,i) in unitOptions"
          :key="i in unitOptions"
        >
          <bm-marker
            :position="{lng:unit.lng, lat: unit.lat}"
            :dragging="false"
            @click="toUnitDetail(i)"
            @mouseover="infoWindowOpen(unit)"
            @mouseout="infoWindowClose(unit)"
          />
          <bm-info-window :position="{lng:unit.lng, lat: unit.lat}" :show="unit.show">{{ unit.name }} <br>
          </bm-info-window>
        </div>

      </baidu-map>

    </el-card>
    <!--======================================表单======================================================-->

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
    >
      <el-form
        ref="dataForm"
        :rules="formRules"
        :model="temp"
        label-width="80px"
      >

        <el-form-item prop="id" label="单位编号">
          <el-input v-model="temp.id" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="name" label="名称">

          <el-input v-model="temp.name" style="width: 300px" />
        </el-form-item>

      </el-form>

      <div>
        <BmapSelector
          @getAddress="getAddress"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createUnit():updateUnit()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!--======================================END=========================================================-->

  </div>
</template>

<script>
import BmapSelector from '@/views/map/components/BmapSelector'
import { addUnit, deleteUnit, getUnitList, updateUnit } from '@/api/unit'

export default {
  components: { BmapSelector },
  props: {
  },

  data() {
    return {
      queryVo: {
        query: { queryInfo: '' },
        pageNum: 1,
        pageSize: 5
      },
      currentCenter: {
        lng: 118.649691,
        lat: 24.941118
      },
      unitList: [],
      unitOptions: [],
      show: false,

      dialogFormVisible: false,

      dialogStatus: '',

      temp: {
        id: null,
        name: null,
        address: null,
        lng: null,
        lat: null
      },

      tempBmMaker: null,

      location: '',
      keyword: '',

      textMap: {
        update: '修改',
        create: '添加'
      },

      formRules: {
        id: [
          { required: true, message: '请输入实验室号', trigger: 'blur' }

        ],
        name: [
          { required: true, message: '请输入实验室名称', trigger: 'blur' }

        ],
        unit: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }

        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }

        ]
      }
    }
  },
  computed: {},

  watch: {},

  mounted() {
    getUnitList(this.queryVo).then(response => {
      this.unitList = response.data.list

      this.unitList.forEach((unit) => {
        const unitOption = {
          name: unit.name,
          lng: unit.lng,
          lat: unit.lat,
          show: false
        }

        this.unitOptions.push(unitOption)
      })
    })
  },
  methods: {
    refresh() {
      this.reload()
    },
    /* ==========================================地图显示相关===================================================*/

    infoWindowOpen(unit) {
      unit.show = true
    },
    infoWindowClose(unit) {
      unit.show = false
    },

    handleChooseUnit(command) {
      this.currentCenter.lat = this.unitOptions[command].lat
      this.currentCenter.lng = this.unitOptions[command].lng
      console.log(this.unitOptions[command].lat, this.unitOptions[command].lng)
      console.log(this.currentCenter.lat, this.currentCenter.lng)
    },

    /* ==========================================END===================================================*/

    /* ==========================================表单相关===================================================*/

    getAddress(address) {
      console.log(address)
      const { name, lat, lng } = address
      this.temp.address = name
      this.temp.lat = lat
      this.temp.lng = lng
    },

    resetTemp() {
      this.temp = {
        id: null,
        name: null,
        address: null,
        lng: null,
        lat: null
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createUnit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUnit(this.temp).then(() => {
            getUnitList(this.queryVo).then(response => {
              this.unitList = response.data.list
              this.totalCount = response.data.total
            })

            this.dialogFormVisible = false

            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.refresh()
          })
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateUnit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUnit(tempData).then(() => {
            getUnitList(this.queryVo).then(response => {
              this.unitList = response.data.list
              this.totalCount = response.data.total
            })

            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleDeleteUnit(unit) {
      this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUnit(unit).then(() => {
          getUnitList(this.queryVo).then(response => {
            this.labList = response.data.list
          })

          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    /* ==========================================END===================================================*/

    /* ==========================================路由相关===================================================*/

    toUnitDetail(i) {
      this.$router.push({
        name: 'unit',
        params: {
          unit: this.unitList[i],
          fromMap: true
        }
      })
    }

    /* ==========================================END===================================================*/

  }
}
</script>
<style scoped>
.unit-list-menu {

}
.map {
  width: 100%;
  height: 470px;
}
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
